/*
 * PAdministradorEntidades.java
 *
 * Created on 3 de abril de 2006, 10:29 AM
 */

package ig.metrica.ui.origenesdedatos;

import ig.metrica.modelos.entity.ModeloorigenesdatosDTO;
import ig.metrica.ui.interfaces.comunes.IMetodosPantallas;
import ig.metrica.ui.pantallas.comunes.ManipulacionDatos;
import ig.util.CodigoBotones;
import ig.util.MyTableModel;
import ig.util.NoContinuaException;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author  jsanchez
 */
public class PAdministradorEntidades extends javax.swing.JPanel implements IMetodosPantallas{
    ManipulacionDatos mpd = null;
    MAdministradorEntidades modelo=null;
    MyTableModel modeloTabla=null;
    String[] nomCol={"Id","Nombre","Conexion"};
    boolean[] edit={false,false,false};
    private String nobreModelo=null;
    //private Integer idModelo=-1;
    /** Creates new form PAdministradorEntidades */
    public PAdministradorEntidades(JFrame frame) throws NoContinuaException {
        initComponents();
        mpd = new ManipulacionDatos(true,false);
        mpd.setLimpiarComponentes(true);
        mpd.setConfimacioSalir(true,"Desea cerrar la ventane del Administrador de entidades");
        mpd.setPanelMetodosPantalla(this);
        mpd.setSize(700,600);
        mpd.setTitle("Administrador de Modelos");
        modelo=new MAdministradorEntidades(this);
        try {
            modelo.buscar();
        } catch (NoContinuaException ex) {
            throw ex;
        }
        mpd.setEstado(CodigoBotones.salir);
        this.Table.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(40);
        this.Table.getTableHeader().getColumnModel().getColumn(1).setWidth(200);
        this.Table.getTableHeader().getColumnModel().getColumn(1).setMaxWidth(200);
        this.Table.getTableHeader().getColumnModel().getColumn(2).setWidth(200);
        this.Table.getTableHeader().getColumnModel().getColumn(2).setMaxWidth(200);

        jLabel1.setVisible(false);
        jLabel2.setVisible(false);
        jLabel3.setVisible(false);
        TextCampos.setVisible(false);
        TextID.setVisible(false);
        TextNombre.setVisible(false);
    }
    public PAdministradorEntidades(String nobreModelo,Integer idModelo) throws NoContinuaException {
        initComponents();
        mpd = new ManipulacionDatos(true,false);
        mpd.setLimpiarComponentes(true);
        mpd.setConfimacioSalir(true,"Desea cerrar la ventane del Administrador de entidades");
        mpd.setPanelMetodosPantalla(this);
        mpd.setSize(700,600);
        mpd.setTitle("Administrador de Modelos");
        //mpd.setLimpiarComponentes(false);
        modelo=new MAdministradorEntidades(this);
        this.nobreModelo=nobreModelo;
        modelo.setNombreModelo(nobreModelo);
        modelo.setIdModelo(idModelo);
        try {
            modelo.buscar();
        } catch (NoContinuaException ex) {
            throw ex;
        }
        mpd.setEstado(CodigoBotones.salir);
        this.Table.setEnabled(false);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        TextID = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        TextNombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        TextCampos = new javax.swing.JTextField();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        TextAQuery = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        Table = new javax.swing.JTable();

        jLabel1.setText("Consecutivo");

        TextID.setFont(new java.awt.Font("Dialog", 0, 11)); // NOI18N
        TextID.setDisabledTextColor(new java.awt.Color(0, 0, 0));

        jLabel2.setText("Nombre");

        TextNombre.setFont(new java.awt.Font("Dialog", 0, 11)); // NOI18N
        TextNombre.setDisabledTextColor(new java.awt.Color(0, 0, 0));

        jLabel3.setText("Campos");

        TextCampos.setFont(new java.awt.Font("Dialog", 0, 11)); // NOI18N
        TextCampos.setDisabledTextColor(new java.awt.Color(0, 0, 0));

        jSplitPane1.setBorder(null);
        jSplitPane1.setDividerLocation(350);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setOneTouchExpandable(true);

        TextAQuery.setColumns(20);
        TextAQuery.setRows(5);
        TextAQuery.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        TextAQuery.setName("NO_ALL"); // NOI18N
        jScrollPane2.setViewportView(TextAQuery);

        jSplitPane1.setBottomComponent(jScrollPane2);

        Table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id ", "Nombre", "Campos"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        Table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        Table.setName("NO_ALL"); // NOI18N
        Table.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                TableKeyPressed(evt);
            }
        });
        Table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                TableMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                TableMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(Table);

        jSplitPane1.setLeftComponent(jScrollPane1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 699, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(TextID, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 68, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(jLabel2)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(TextNombre, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE))
                            .add(TextCampos, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jLabel2)
                    .add(TextNombre, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(TextID, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(TextCampos, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 533, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    
    private void TableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableMousePressed
        
    }//GEN-LAST:event_TableMousePressed
    
    private void TableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableMouseReleased
        if(Table.isEnabled()){
            jScrollPane1.setEnabled(false);Table.setEnabled(false);
            actualizarText();
            update(-1);
            jScrollPane1.setEnabled(true);Table.setEnabled(true);
            Table.requestFocusInWindow();
        }
    }//GEN-LAST:event_TableMouseReleased
    
    private void TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableMouseClicked
        //mpd.setEstado(CodigoBotones.grupoBuscarPresionado);
//    if(Table.isEnabled()){
//        Table.setEnabled(false);
////            Object obj=Table.getValueAt(Table.getSelectedRow(),0);
////            if(Table.getSelectedColumn()>1 && (obj.equals(IOrigenesDatos.LIBROS_CUENTAS_PRODUCTOS)
////                || obj.equals(IOrigenesDatos.ESPECIES)
////                || obj.equals(IOrigenesDatos.MONEDASVALORES)
////                || obj.equals(IOrigenesDatos.TASAS))){
////                Table.setValueAt(true,Table.getSelectedRow(),Table.getSelectedColumn());
////            }
//            actualizarText();
//            update(-1);
//            Table.setEnabled(true);
//            Table.requestFocusInWindow();
//        }
    }//GEN-LAST:event_TableMouseClicked
    
    private synchronized void update(int tecla){
        ModeloorigenesdatosDTO dto=null;
        Integer key=null;
        if((tecla==32 || tecla==-1)&& Table.getValueAt(this.Table.getSelectedRow(),this.Table.getSelectedColumn())  instanceof Boolean){
            dto=new ModeloorigenesdatosDTO();
            Integer origendato=( (Integer) Table.getValueAt(this.Table.getSelectedRow(),0)  );
            Boolean modelo=!( (Boolean) Table.getValueAt(this.Table.getSelectedRow(),this.Table.getSelectedColumn())    );
//            if(tecla==32)
//                modelo=!modelo;
            Integer idModelo=this.modelo.getIdModelo(this.modeloTabla.getColumnName(this.Table.getSelectedColumn()));
            key=Integer.valueOf(idModelo+""+origendato);

            /***************/
            dto.setModelo(idModelo);
            dto.setOrigenesdatos(origendato);
            /***************/
            if(modelo)
                this.modelo.addDTO(key,dto);
            else
                this.modelo.remove(key);
            mpd.setEstado(CodigoBotones.grupoModificarPresionado);
        }
        //modelo.addDTO(key,dto);
        //modelo.remove(key);
    }
    
    private void TableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TableKeyPressed
        if(Table.isEnabled()){
            jScrollPane1.setEnabled(false);Table.setEnabled(false);
            update(evt.getKeyCode());
            mpd.habilitaControles(false);
            mpd.setEstado(CodigoBotones.grupoBuscarPresionado);
            if(evt.getKeyCode()==38 && Table.getSelectedRow()>0){//arriba
                this.TextID.setText(String.valueOf(modelo.getData()[Table.getSelectedRow()-1][0]));
                this.TextNombre.setText((String) modelo.getData()[Table.getSelectedRow()-1][1]);
                this.TextCampos.setText((String)modelo.getData()[Table.getSelectedRow()-1][2]);
                this.TextAQuery.setText((String)modelo.getData()[Table.getSelectedRow()][3].toString());
            }else if(evt.getKeyCode()==40 && Table.getSelectedRow()<Table.getRowCount()-1){//abajo
                this.TextID.setText(String.valueOf(modeloTabla.getObjet()[Table.getSelectedRow()+1][0]));
                this.TextNombre.setText((String)modelo.getData()[Table.getSelectedRow()+1][1]);
                this.TextCampos.setText((String)modelo.getData()[Table.getSelectedRow()+1][2]);
                this.TextAQuery.setText((String)modelo.getData()[Table.getSelectedRow()][3].toString());
            }
            jScrollPane1.setEnabled(true);Table.setEnabled(true);
            Table.requestFocusInWindow();
        }
    }//GEN-LAST:event_TableKeyPressed
    
    private void actualizarText(){
        //if(Table.isEnabled()){
        try {
            this.TextID.setText(String.valueOf(modelo.getData()[Table.getSelectedRow()][0]));
            this.TextNombre.setText((String) modelo.getData()[Table.getSelectedRow()][1]);
            this.TextCampos.setText((String) modelo.getData()[Table.getSelectedRow()][2]);
            this.TextAQuery.setText((String)modelo.getData()[Table.getSelectedRow()][3].toString());
//            this.TextID.setText(String.valueOf(Table.getValueAt(Table.getSelectedRow(),0)));
//            this.TextNombre.setText((String) Table.getValueAt(Table.getSelectedRow(),1));
            
//            this.TextCampos.setText((String)Table.getValueAt(Table.getSelectedRow(),2));
            //}
        } catch (Exception e) {/*System.out.println("bep");*/}
    }
    public void setData(Object[][] data){
        if(modeloTabla==null){
            modeloTabla= new MyTableModel(data,nomCol,edit);
            Table.setModel(modeloTabla);
        }else
            modeloTabla.setData(data);
        Table.updateUI();
        if(this.nobreModelo!=null)
            Table.setEnabled(false);
        Table.getTableHeader().setReorderingAllowed(false);
    }
    public JInternalFrame getInternalFrame() {
        return this.mpd;
    }
    
    public void validar() throws NoContinuaException {
    }
    
    public void guardar() throws NoContinuaException {
        if(this.nobreModelo!=null || JOptionPane.showConfirmDialog(this," ¿ Desea guardar los cambios ? ","Mensaje" ,JOptionPane.OK_CANCEL_OPTION)==0){
            modelo.guardar();
            modelo.buscar();
            mpd.setEstado(CodigoBotones.salir);
            if(this.nobreModelo==null)
                JOptionPane.showMessageDialog(this,"Se guardaron los cambios","Mensaje" ,JOptionPane.OK_CANCEL_OPTION);
        }else
            mpd.setEstado(CodigoBotones.grupoModificarPresionado);
    }
    
    public void buscar() throws NoContinuaException {
        this.setEnabled(false);
        modelo.buscar();
        this.setEnabled(true);
    }
    
    public void modificar() throws NoContinuaException {
        //actualizarText();
        jScrollPane1.setEnabled(true);
        this.Table.setEnabled(true);
    }
    
    public void nuevo() throws NoContinuaException {
    }
    
    public void eliminar() throws NoContinuaException {
    }
    
    public void salir() throws NoContinuaException {
    }
    
    public void imprimir() throws NoContinuaException {
    }
    
    public void cancelar() throws NoContinuaException {
        try {
            buscar();
        } catch (NoContinuaException ex) {
            throw ex;
        }
        mpd.setEstado(CodigoBotones.grupoBuscarPresionado);
        actualizarText();
    }
    
    public Component[] getControles() {
        return null;
    }
    
    public void setFrame(JFrame frame) {
    }
    
    public JFrame getFrame() {
        return null;
    }
    
    public String[] getNomCol() {
        return nomCol;
    }
    
    void resetColumnas(){
        nomCol= new String[3];
        nomCol[0]="Id";
        nomCol[1]="Nombre";
        nomCol[2]="Conexion";
        //{"Consecutivo","Nombre"};
    }
    void addColumna(String string) {
        boolean[] colnedit=edit.clone();
        String[] clon=nomCol.clone();
        
        nomCol=new String[clon.length+1];
        edit=new boolean[colnedit.length+1];
        for (int i = 0; i < clon.length; i++) {
            nomCol[i]=clon[i];
            edit[i]=colnedit[i];
        }
        nomCol[clon.length]=string;
        edit[colnedit.length]=new Boolean(true);
    }
    
    public void setIdModelo(int i) {
        //this.idModelo=i;
        this.modelo.setIdModelo(i);
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable Table;
    private javax.swing.JTextArea TextAQuery;
    private javax.swing.JTextField TextCampos;
    private javax.swing.JTextField TextID;
    private javax.swing.JTextField TextNombre;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    // End of variables declaration//GEN-END:variables
    
}
